package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.behavior.service.BehaviorService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.UpdateArticleInfo;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnLikeBehaviorDto;
import com.heima.model.behavior.pojos.UserBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.heima.model.behavior.dtos.LikeBehaviorDTO;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author:Dikk
 * @create: 2023-08-02 16:50
 * @Description: BehaviorServiceImpl
 */
@Service
@Slf4j
public class BehaviorServiceImpl implements BehaviorService {
    @Autowired
    private CacheService cacheService;

//    @Autowired
//    private IArticleClient articleClient;
    @Autowired
    private KafkaTemplate kafkaTemplate;


    /**
     * 不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLikeBehavior(UnLikeBehaviorDto dto) {
        // 如果获取的文章id为空
        if (dto.getArticleId() == null) {
            // 检查参数，如果dto的文章对象为空
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 从当前线程中获取ApUser对象
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            // 检查用户登录状态，如果用户未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        UserBehavior userBehavior = new UserBehavior();
        if (dto.getType() == 0) {
            userBehavior.setIsUnlike(true);
            // 如果传入的dto的type字段为0，表示用户执行了"取消不喜欢"的操作
            log.info("保存当前key:{},{},{}", dto.getArticleId(), user.getId(), dto);

            // 将不喜欢行为相关数据保存到 Redis 中，使用 HSet 命令
            cacheService.hPut(user.getId().toString(), dto.getArticleId().toString(), JSON.toJSONString(userBehavior));
        } else {
            userBehavior.setIsUnlike(false);
            // 如果传入的dto的type字段不为0，表示用户执行了"不喜欢"的操作
            log.info("删除当前key:{},{},{}", dto.getArticleId(), user.getId(), dto);
            // 将不喜欢行为相关数据从 Redis 中删除，使用 HDel 命令
            cacheService.hPut(user.getId().toString(), dto.getArticleId().toString(), JSON.toJSONString(userBehavior));
        }

        // 操作成功，返回成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 阅读次数
     *
     * @param dto 到
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = ApUserThreadLocalUtil.getUser();
        //查询是否登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询是否有阅读记录
        String readBehaviorCount = (String) cacheService.hGet(user.getId().toString(), dto.getArticleId().toString());
        //有记录，增加阅读数
        if (StringUtils.isNotBlank(readBehaviorCount)){
            UserBehavior userBehavior = JSON.parseObject(readBehaviorCount, UserBehavior.class);
            userBehavior.setCount(userBehavior.getCount()+dto.getCount());
            cacheService.hPut(user.getId().toString(), dto.getArticleId().toString(), JSON.toJSONString(userBehavior));

        }else {

            //无记录，新增阅读记录
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setCount(1);
            cacheService.hPut(user.getId().toString(), dto.getArticleId().toString(), JSON.toJSONString(userBehavior));
        }

        //更新文章信息
        UpdateArticleInfo updateArticleInfo = new UpdateArticleInfo();
        updateArticleInfo.setArticleId(dto.getArticleId());
        updateArticleInfo.setCount(1);
        kafkaTemplate.send(ArticleConstants.ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleInfo));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 是否点赞文章
     *
     * @param likeBehaviorDTO
     * @return
     */
    @Override
    public ResponseResult likesBehavior(LikeBehaviorDTO likeBehaviorDTO) {

        //参数校验
        if (Objects.isNull(likeBehaviorDTO)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取文章
        Long articleId = Long.valueOf(likeBehaviorDTO.getArticleId());

        Integer userId = ApUserThreadLocalUtil.getUser().getId();

        //获取redis中的hashmap的值
        String data = (String) cacheService.hGet(userId.toString(), articleId.toString());

        //解析参数
        UserBehavior userBehavior = JSON.parseObject(data, UserBehavior.class);

        if (Objects.isNull(userBehavior)) {
            userBehavior = new UserBehavior();
        }
        //判断type是否为0 0为文章
        if (likeBehaviorDTO.getType() == 0) {
            userBehavior.setIsLike(likeBehaviorDTO.getOperation() == 0 ? true : false);
            //
        }

        //存入redis中
        cacheService.hPut(userId.toString(), articleId.toString(), JSON.toJSONString(userBehavior));

        //更新文章信息
        UpdateArticleInfo updateArticleInfo = new UpdateArticleInfo();
        updateArticleInfo.setArticleId(Long.valueOf(likeBehaviorDTO.getArticleId()));
        Integer likes=likeBehaviorDTO.getOperation()==0?1:(-1);
        updateArticleInfo.setLikes(likes);
        kafkaTemplate.send(ArticleConstants.ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleInfo));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}